<?php
declare (strict_types=1);

namespace app\admin\controller\tally;

use app\admin\controller\CommonController;
use app\common\model\AclUser;
use app\common\model\TallyCustom;
use app\common\model\TallyProgressDay;
use app\common\model\TallyProgressMonth;
use app\common\model\TallyTodo;
use ffhome\common\util\DateUtil;
use ffhome\frame\service\DictDataService;
use think\db\BaseQuery;

class Todo extends CommonController
{
    protected $modelName = TallyTodo::MODEL_NAME;
    protected $alias = 't';

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(TallyProgressDay::MODEL_NAME . ' d', "d.id={$this->alias}.day_id")
            ->leftJoin(TallyProgressMonth::MODEL_NAME . ' m', "m.id={$this->alias}.month_id")
            ->leftJoin(AclUser::MODEL_NAME . ' a', "a.id=d.accounting_id")
            ->leftJoin(TallyCustom::MODEL_NAME . ' c', "c.id=m.custom_id");
    }

    protected function getSearchFields(): string
    {
        return "d.progress_date,c.name custom_name,concat(a.username,a.nickname) accounting_name,{$this->alias}.content"
            . ",{$this->alias}.day_id,{$this->alias}.month_id,{$this->alias}.estimate_time,{$this->alias}.actual_time"
            . ",{$this->alias}.completion_status";
    }

    protected function getSearchDefaultSort(): array
    {
        return ["d.progress_date" => 'asc'];
    }

    protected function onAfterEdit(array &$data, array $row)
    {
        parent::onAfterEdit($data, $row);
        if (isset($data['completion_status'])) {
            TallyProgressDay::updateCompletionStatus($row['day_id']);
        }
    }

    protected function getExportHeader()
    {
        return [
            [lang('day.progress_date'), 'progress_date'],
            [lang('accounting.name'), 'accounting_name'],
            [lang('custom.name'), 'custom_name'],
            [lang('day.content'), 'content'],
            [lang('common.estimate_time_alias'), 'estimate_time'],
            [lang('common.actual_time_alias'), 'actual_time'],
            [lang('day.completion_status'), 'completion_status'],
        ];
    }

    protected function convertExportData(&$list)
    {
        foreach ($list as &$vo) {
            $vo['progress_date'] = $vo['progress_date'] . '[' . DateUtil::week($vo['progress_date']) . ']';
            $vo['completion_status'] = DictDataService::getNameByValue($vo['completion_status'], 'completion_status_list');
        }
    }

    public function generateEmpty($day_id)
    {
        $id = TallyTodo::createEmpty($day_id);
        $monthList = TallyProgressMonth::getMonthListByDayId($day_id);
        $this->success('', ['id' => $id, 'list' => $monthList]);
    }
}
